package cn.itcast.wanxinp2p.account.service.impl;

import cn.itcast.wanxinp2p.account.common.AccountErrorCode;
import cn.itcast.wanxinp2p.account.entity.Account;
import cn.itcast.wanxinp2p.account.mapper.AccountMapper;
import cn.itcast.wanxinp2p.account.service.AccountService;
import cn.itcast.wanxinp2p.account.service.SmsService;
import cn.itcast.wanxinp2p.api.account.model.AccountDTO;
import cn.itcast.wanxinp2p.api.account.model.AccountLoginDTO;
import cn.itcast.wanxinp2p.api.account.model.AccountRegisterDTO;
import cn.itcast.wanxinp2p.common.domain.BusinessException;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import cn.itcast.wanxinp2p.common.util.PasswordUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.Hmily;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Resource
    private SmsService smsService;

    @Value("${sms.enable}")
    private Boolean smsEnable;

    @Override
    public RestResponse getSMSCode(String mobile) {
        return smsService.getSMSCode(mobile);
    }

    @Override
    public Integer checkMobile(String mobile, String key, String code) {
        // 校验验证码
        smsService.verifySmsCode(key, code);
        // 校验手机号
        QueryWrapper<Account> queryWrapper = new QueryWrapper();
        //queryWrapper.eq("mobile", mobile);
        queryWrapper.lambda().eq(Account::getMobile, mobile);
        int count = this.count(queryWrapper);
        return count > 0 ? 1 : 0;
    }

    @Hmily(confirmMethod = "confirmRegister", cancelMethod = "cancelRegister")
    @Override
    public AccountDTO register(AccountRegisterDTO accountRegisterDTO) {
        // 统一用户保存注册信息
        Account account = new Account();
        account.setUsername(accountRegisterDTO.getUsername());
        account.setMobile(accountRegisterDTO.getMobile());
        account.setPassword(PasswordUtil.generate(accountRegisterDTO.getMobile()));
        if (smsEnable) {
            account.setPassword(PasswordUtil.generate(accountRegisterDTO.getMobile()));
        }
        account.setDomain("c");
        this.save(account);
        return convertAccountEntityToDTO(account);
    }

    public void confirmRegister(AccountRegisterDTO registerDTO) {
        log.info("execute confirmRegister");
    }

    public void cancelRegister(AccountRegisterDTO registerDTO) {
        log.info("execute cancelRegister");
        //删除账号
        remove(Wrappers.<Account>lambdaQuery().eq(Account::getUsername,
                registerDTO.getUsername()));
    }

    @Override
    public AccountDTO login(AccountLoginDTO accountLoginDTO) {
        Account account = null;
        if ("c".equalsIgnoreCase(accountLoginDTO.getDomain())) {
            // 如果是c端用户，则根据手机号查询
            account = getAccountByMobile(accountLoginDTO.getMobile());
        } else {
            // 如果是b端用户，则根据用户名查询
            account = getAccountByUserName(accountLoginDTO.getUsername());
        }
        // 用户不存在
        if (account == null) {
            throw new BusinessException(AccountErrorCode.E_130104);
        }
        AccountDTO accountDTO = convertAccountEntityToDTO(account);
        if (smsEnable) {
            // 如果使用短线验证码登录无需校验密码
            return accountDTO;
        }
        // 密码校验
        if (!PasswordUtil.verify(accountLoginDTO.getPassword(), account.getPassword())) {
            throw new BusinessException(AccountErrorCode.E_130105);
        }
        return accountDTO;
    }

    /**
     * 根据手机号查询账号
     *
     * @param mobile
     * @return
     */
    private Account getAccountByMobile(String mobile) {
        return this.getOne(new QueryWrapper<Account>().lambda().eq(Account::getMobile, mobile));
    }

    /**
     * 根据用户名查询账号
     *
     * @param username
     * @return
     */
    private Account getAccountByUserName(String username) {
        return this.getOne(new QueryWrapper<Account>().lambda().eq(Account::getUsername, username));
    }

    /**
     * * entity转为dto
     *
     * @param entity
     * @return
     */
    private AccountDTO convertAccountEntityToDTO(Account entity) {
        if (entity == null) {
            return null;
        }
        AccountDTO dto = new AccountDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }
}
